package com.bingo.generate.comm.util;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.*;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName
 * Description
 * Create by lc
 * Date 2021/7/18 16:23
 */
public class FmUtil {

    private static Configuration single;

    public static Template getDefinedTemplate(String templateName) {
        try {
            //配置类
            if(single==null){
                Configuration cfg = new Configuration();
                cfg.setDirectoryForTemplateLoading(PathUtils.getResPath("ftl").toFile());
                cfg.setDefaultEncoding("UTF-8");
                cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
                single=cfg;
            }
            return single.getTemplate(templateName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void print(String templateName, Map map){
        if(map==null){
            map=new HashMap<>();
        }
        Template template=getDefinedTemplate(templateName);
        BeansWrapper wrapper = new BeansWrapper();
        //  声明可以使用静态方法
        TemplateModel statics = wrapper.getStaticModels();
        map.put("statics",statics);
        //3.加载模板文件
        //4.显示生成的数据,//将合并后的数据打印到控制台
        StringWriter out = new StringWriter();
        try {
            template.process(map,out);
            out.flush();
            System.out.println(out.toString());
            //5.关闭
            out.close();
            /*
            Thread.sleep(1000);
            */
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    public static void printComm(String templateName, Map map){
        if(map==null){
            map=new HashMap<>();
        }
        Template template=getDefinedTemplate(templateName);
        BeansWrapper wrapper = new BeansWrapper();
        //  声明可以使用静态方法
        TemplateModel statics = wrapper.getStaticModels();
        map.put("statics",statics);
        StringWriter stringWriter = new StringWriter();
        //3.加载模板文件
        //4.显示生成的数据,//将合并后的数据打印到控制台
        String result=null;
        try {
            template.process(map,stringWriter);
            stringWriter.flush();
            //5.关闭
            result=stringWriter.toString();
            stringWriter.close();
            /*
            Thread.sleep(1000);
            */
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
    }

    public static void print(String templateName){
        print(templateName,null);
    }

}
